<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use app\common\model\MoneyLog;
use app\common\model\OrderMore;
use app\common\model\Packages;
use app\common\model\User;
use app\common\model\UserPackagesConfig;
use fast\Random;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\db\exception\BindParamException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *用户订单
 * @icon fa fa-circle-o
 */
class Orderagency extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("isCallbackList", $this->model->getIsCallbackList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("isRechargedList", $this->model->getIsRechargedList());
        $this->view->assign("isHexiaoList", $this->model->getIsHexiaoList());
        $this->view->assign("platformTypeList", $this->model->getPlatformTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'packages'])
                ->where($where)
                ->where(['order.is_agency' => 2])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->visible([
                    'id',
                    'shipping_contact',
                    'shipping_phone',
                    'shipping_idcard',
                    'shipping_province',
                    'shipping_city',
                    'shipping_area',
                    'shipping_address',
                    'is_callback',
                    'order_id',
                    'phone',
                    'order_status',
                    'rebate',
                    'shipping_company_name',
                    'shipping_no',
                    'is_recharged',
                    'createtime',
                    'callback_time',
                    'recover_status',
                    'audit_status',
                    'baoxiao_status',
                    'user_rebate',
                    'admin_image',
                    'parent_id',
                    'is_more',
                    'more_num',
                    'is_hexiao',
                    'platform_type',
                    'image',
                    'jiesuan_time',
                    'is_tripartite_settlement',
                    'audit_upload_time',
                    'audit_time',
                    'remark',
                    'error_msg',
                    'rebate_recover_msg'
                ]);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['username', 'mobile']);
                $row->visible(['packages']);
                $row->getRelation('packages')->visible(['name', 'user_name','supplier']);
            }

            $result = array ("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!empty($params['baoxiao_status'])) {
            if ($params['baoxiao_status'] == 2) {
                $params['baoxiao_time'] = time();
            }
        }
        $params['is_up'] = 2;

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if (!empty($params['image'])) {
                $params['audit_upload_time'] = time();

            }
            if (!empty($params['error_msg'])) {
                $params['is_up']             = 1;
                $params['audit_status']      = 0;
                $params['call_image']        = 0;
            }else{
                if ($row['order_status'] == 5) {
                    $this->error('订单已经结算过了');
                }
                if ($params['order_status'] == 5) {
                    $params['settlement_time'] = time();
                    orderfencheng($row['id'],$row['goods_id']);
//                    $userData                  = findAncestors($row['user_id']);
//                    $packageInfo               = Packages::where(['id' => $row['goods_id']])->find();
//                    if (!$userData) {
//                        $config = new UserPackagesConfig();
//                        $rebate = $config->where(['user_id'=>$row['user_id'],'packages_id'=>$row['goods_id']])->value('money');
//                        if($rebate){
//                            $packageInfo['rebate']  = $rebate;
//                        }
//                        //顶级代理下单
//                        dingji($row['user_id'], $row['id'], $row['goods_id'], $packageInfo['rebate'], false, true);
//                    } else {
//                        array_unshift($userData, $row['user_id']);
//                        $money = moneydigui($row['user_id'], $row['goods_id']);
//                        if ($money) {
//                            digui($row['user_id'], $money, $row['goods_id'], $row['id'], 0, true);
//                        } else {
//                            //顶级
//                            $config = new UserPackagesConfig();
//                            $rebate = $config->where(['user_id'=>$row['user_id'],'packages_id'=>$row['goods_id']])->value('money');
//                            if($rebate){
//                                $packageInfo['rebate']  = $rebate;
//                            }
//                            dingji($userData[count($userData) - 1], $row['id'], $row['goods_id'], $packageInfo['rebate'],
//                                false, true);
//                        }
//                    }
                }
            }

            $result = $row->allowField(true)->save($params);

            if (!empty($params['baoxiao_status']) && $result) {
                if ($params['baoxiao_status'] == 2) {
                    $userModel    = new User();
                    $value        = 0;
                    $packagesInfo = \app\admin\model\Packages::where(['id' => $row['goods_id']])->find();
                    if (isset($packagesInfo['epact_set_meal']) && isset($packagesInfo['ciyue_set_meal'])) {
                        $jie_day = date('d');
                        if ($jie_day > 30) {
                            $jie_day = 30;
                        }
                        $value = round((30 - $jie_day) * ($packagesInfo['epact_set_meal'] / 30) + ($packagesInfo['ciyue_set_meal'] * 2),
                            2);
                    }
                    if ($value > 0) {
                        $userModel->money($value, $row['user_id'], '话费报销', $row['id'], $packagesInfo['id']);
                    }

                }
            }

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function jssb($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        if(empty($params['error_msg'])){
//            $this->error(__('请填写失败原因', ''));
//        }
        $params = $this->preExcludeFields($params);
        if ($params['audit_status'] == 2 && !empty($params['zhui_money']) && $params['zhui_money'] == 2) {
            $this->error(__('审核通过就不能追回佣金', ''));
        }
        if($row['jsms_text'] == '已全部结算'){
            $this->error(__('订单已全部结算不能操作', ''));
        }
        $result = false;
        Db::startTrans();
        try {
            $packageInfo = Packages::where(['id' => $row['goods_id']])->find();
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if ($params['error_msg'] != $row['error_msg']) {
                $params['is_up']             = 1;
                $params['audit_status']      = 0;
                $params['call_image']        = '';
                $params['image']             = '';
                $params['baoxiao_status']    = '-2';
            }
            //审核通过
            if ($params['audit_status'] == 2) {
                $more_num = $row['more_num']+1;
                jiesuan($row, $packageInfo,$more_num);
                $params['order_status']    = 5;
                $params['settlement_time'] = time();
                $params['baoxiao_time']    = time();
                if ($row['is_more'] == 2) {
                    $params['more_num']    = $more_num;
                    $params['two_js_time'] = settlement_time($params['settlement_time']);//二次结算时间;
                }
                $params['error_msg'] = '';
                $params['baoxiao_status'] = 1;
                if ($packageInfo['day'] != 6) {
                    $params['hexiao_next_time'] = 7 * 86400 + time();
                } else {
                    $params['hexiao_next_time'] = settlement_time(time());
                }
                if(empty($params['two_js_time'])){
                    $params['two_js_time'] = $params['hexiao_next_time'];
                }
            }
            if($params['audit_status'] == 3){
                $params['baoxiao_status']  = '-1';
                $params['reason'] =  $params['error_msg'];
            }
            //佣金追回
            if(!empty($params['zhui_money']) && $params['zhui_money'] == 2){
                if(!$params['rebate_recover_msg']){
                    $this->error(__('请填写追回原因', ''));
                }
                zhuihui($row,$params['rebate_recover_msg']);
                $params['order_status']   = 0;
                $params['recover_status'] = 2;
                $params['recover_time']   = time();
            }
            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 审核订单
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if ($row['is_agency'] == 2) {
                $row['image'] = config('site.user_url').$row['image'];
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($params['audit_status'] == 0) {
            $this->error('请选择审核状态');
        }
        $packageInfo = Packages::where(['id' => $row['goods_id']])->find();
        if ($params['audit_status'] == 2) {
            if ($row['is_tripartite_settlement'] == 1) {
                $more_num = $row['more_num']+1;
                jiesuan($row, $packageInfo,$more_num);
                $params['order_status']    = 5;
                $params['settlement_time'] = time();
                $params['baoxiao_time']    = time();
                if ($row['is_more'] == 2) {
                    $params['more_num']    = $more_num;
                    $params['two_js_time'] = settlement_time($params['settlement_time']);//二次结算时间;
                }
            } else {
                if($row['order_status'] !=5){
                    $params['order_status'] = 4;
                }
            }
            $params['error_msg'] = '';
            $params['baoxiao_status'] = 1;
            if ($packageInfo['day'] != 6) {
                $params['hexiao_next_time'] = 7 * 86400 + time();
            } else {
                $params['hexiao_next_time'] = settlement_time(time());
            }
            if(empty($params['two_js_time'])){
                $params['two_js_time'] = $params['hexiao_next_time'];
            }
        }

        if($params['audit_status'] == 3){
            if(!$params['reason']){
                $this->error('请填写驳回原因');
            }
            $params['baoxiao_status']  = '-1';
        }
        unset($params['image']);
        $params['audit_time'] = time();
        $params               = $this->preExcludeFields($params);
        $result               = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 佣金追回
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function recover($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if ($row['recover_status'] == 1) {
                $row['rebate_recover_money'] = $row['user_rebate'] * 2;
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params['recover_status'] = 2;
        $params['recover_time']   = time();
        $params                   = $this->preExcludeFields($params);
        $result                   = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            if ($result) {
                $userModel = new User();
                $userModel->money(-$params['rebate_recover_money'], $row['user_id'],
                    "佣金追回：".$params['rebate_recover_msg'], $row['id'], $row['goods_id']);
            }
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 订单详情
     * @param  null  $ids
     */

    public function orderinfo($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $params['order_id']       = $row['order_id'];
            $params['shipping_phone'] = $row['shipping_phone'];
            $data['appid']            = config('site.ooen_appid');
            $data['timestamp']        = time();
            $data['nonce_str']        = Random::alnum(32);
            $data                     = array_merge($data, $params);
            $string                   = ascll($data);
            $stringSignTemp           = $string.'&appsecret='.config('site.open_appsecret');;
            $data['sign'] = mb_strtoupper(md5($stringSignTemp));
            $url          = "http://agent.haoka.bx10086.cn/v1/haoka_api/orders";//办理套餐
            $res          = httpPost($url, $data);
            $rows         = json_decode($res, true);
            if (empty($rows['rows'][0])) {
                $this->error('未查到信息');
            }
            $this->view->assign('row', $rows['rows'][0]);
            return $this->view->fetch();
        }
    }


    /**
     *  订单处理
     * @param  null  $ids
     */

    public function orderchuli($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (empty($params['image'])) {
            $this->error('请上传截图');
        }
        $params['audit_upload_time'] = time();

        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 订单处理
     * @param  null  $ids
     */

    public function hexiao($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $params['hexiao_time']    = time();
        $params['hexiao_js_time'] = strtotime($params['hexiao_js_time']);
        $params                   = $this->preExcludeFields($params);
        $result                   = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name.'.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if($params['platform_type'] == 6){
            $this->kgjimport($params['image']);
        }else if($params['platform_type'] == 7){
            $supplier = \app\admin\model\Packages::where(['id'=>$params['supplier']])->value('supplier');
            $this->zizhuimport($params['image'],$supplier);
        }else{
            $this->importtwo($params['image']);
        }
    }

    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function importtwo($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        $userModel = new User();
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                if (!empty($values[0]) && !empty($values[1]) && !empty($values[2])) {
                    $orderInfo = $this->model->where([
                        'order_id'   => $values[0],
                        'is_more'    => 2,
                        'import_num' => 0
                    ])->find();
//                    $orderInfo = $this->model->where(['order_id'=>$values[0]])->find();
                    if ($orderInfo) {
                        $orderInfo->import_num += 1;
                        if ($values[1] == "正常" || $values[1] == "在网") {
                            $orderInfo->more_num += 1;

                            $packageInfo = Packages::where(['id' => $orderInfo['goods_id']])->find();
                            $huafei            = $packageInfo['ciyue_set_meal'];
                            if ($huafei) {
                                $userModel::money($huafei, $orderInfo['user_id'], '话费报销', $orderInfo['id'],
                                    $packageInfo['id']);
                            }
                            jiangli($orderInfo, $packageInfo, 1, $orderInfo->more_num);
                            if ($orderInfo['parent_id']) {
                                jiangli($orderInfo, $packageInfo, 2, $orderInfo->more_num);
                            }
                            if ($orderInfo['two_id']) {
                                jiangli($orderInfo, $packageInfo, 3, $orderInfo->more_num);
                            }
                            //区县
                            if ($orderInfo['agency_area_id']) {
                                jiangli($v, $packageInfo, 4, $orderInfo->more_num);
                            }
                            //小区
                            if ($orderInfo['plot_id']) {
                                jiangli($orderInfo, $packageInfo, 5, $orderInfo->more_num);
                            }

                        }
                        if (!$orderInfo->phone) {
                            $orderInfo->phone = $values[2];
                        }
                        $orderInfo->save();
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }


    /**
     * 卡管家导入
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function kgjimport($file)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        $userModel = new User();
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                if (!empty($values[0]) && !empty($values[1]) && !empty($values[4])) {

                    $orderInfo = $this->model->where(['order_id'   => $values[1],'import_num'=>0])->find();
                    if ($orderInfo) {
                        //is_more
                        $orderInfo->import_num += 1;
                        $packageInfo = Packages::where(['id' => $orderInfo['goods_id']])->find();
                        $values[5] = $values[5]??0;
                        $orderInfo->order_status    = 5;
                        $orderInfo->settlement_time = time();
                        $orderInfo->baoxiao_time    = time();
                        $orderInfo->baoxiao_status  = 2;
                        $orderInfo->is_hexiao       = 2;
                        if($orderInfo['is_more'] == 1){
                            if($values[4] && $values[5]){
                                //一次性结算
                                jiesuan($orderInfo,$packageInfo,0);
                            }
                        }else{
                            $orderInfo->is_hexiao       = 5;
                            $orderInfo->baoxiao_status  = 4;
                            jiangli($orderInfo, $packageInfo);
                            if ($orderInfo['parent_id']) {
                                jiangli($orderInfo, $packageInfo, 2);
                            }
                            if ($orderInfo['two_id']) {
                                jiangli($orderInfo, $packageInfo, 3);
                            }
                            //区县
                            if ($orderInfo['agency_area_id']) {
                                jiangli($v, $packageInfo, 4);
                            }
                            //小区
                            if ($orderInfo['plot_id']) {
                                jiangli($orderInfo, $packageInfo, 5);
                            }
                            if($values[5]){
                                $orderInfo->is_hexiao       = 8;
                                $orderInfo->baoxiao_status  = 6;
                                sleep(1);
                                jiangli($orderInfo, $packageInfo,1,2);
                                if ($orderInfo['parent_id']) {
                                    jiangli($orderInfo, $packageInfo, 2,2);
                                }
                                if ($orderInfo['two_id']) {
                                    jiangli($orderInfo, $packageInfo, 3,2);
                                }
                                //区县
                                if ($orderInfo['agency_area_id']) {
                                    jiangli($v, $packageInfo, 4,2);
                                }
                                //小区
                                if ($orderInfo['plot_id']) {
                                    jiangli($orderInfo, $packageInfo, 5,2);
                                }
                            }
                        }
                        if(!empty($values[2])){
                            $orderInfo->phone = $values[2];
                        }
                        $orderInfo->audit_status    = 2;
                        $orderInfo->error_msg       = '';
                        $orderInfo->save();
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }


    /**
     * 自助订单导入
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function zizhuimport($file,$supplier)
    {
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH.DS.'public'.DS.$file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file     = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp       = fopen($filePath, 'w');
            $n        = 0;
            while ($line = fgets($file)) {
                $line     = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line."\n");
                } else {
                    fwrite($fp, '"'.str_replace(['"', ','], ['""', '","'], $line)."\"\n");
                }
                $n++;
            }

            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }
        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table    = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list     = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?",
            [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT']            = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet    = $PHPExcel->getSheet(0);                //读取文件中的第一个工作表
            $allColumn       = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow          = $currentSheet->getHighestRow();        //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields          = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val      = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];

                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();

                    $values[] = is_null($val) ? '' : $val;
                }
                if (!empty($values[0]) && !empty($values[1]) && !empty($values[2]) && !empty($values[3]) && !empty($values[5]) && !empty($values[11])) {
                    $order_status = '1,2,3,4';
                    $orderInfo   = $this->model->where(['order_id'   => $values[1]])->whereIn('order_status', $order_status)->find();
                    $packageInfo = Packages::where(['packages_id' => $values[2],'supplier'=>$supplier,'type'=>3])->find();
                    if(!$orderInfo){
                        $where['shipping_contact'] = $values[5];
                        $where['shipping_phone']   = $values[11];
                        $where['goods_id']         = $packageInfo['id']??0;
                        $orderInfo = $this->model->where($where)->whereIn('order_status', $order_status)->find();
                        if(!$orderInfo && $where['goods_id']){
                            $packageInfo = Packages::where(['id'=>['neq',$where['goods_id']],'packages_id' => $values[2],'supplier'=>$supplier])->whereIn('type','1,2')->find();
                            if($packageInfo){
                                $where['goods_id'] = $packageInfo['id'];
                                $orderInfo = $this->model->where($where)->whereIn('order_status', $order_status)->find();
                            }
                        }
                    }
                    if ($orderInfo) {
                        //is_more
                        $v13 = $values[13]??'';//奖励方式
                        $v12 = $values[12]??'';//商品描述
//                        if($v13 == "首充" || $v13 == "累充"){
//                            //已首充/待结算/首充
//                            if($v12 == '已首充' || $v12 == '待结算' || $v12 == '首充'){
//                                $orderInfo->order_status    = 4;
//                            }
//                            if($v12 == "已激活" || $v12 == "激活" || $v12 == "激活成功"){
//                                $orderInfo->order_status    = 1;
//                            }
//                        }
                        $orderInfo->remark = $v12;
//                        if($v13 == "激活"){
//                            if($v12 == "已激活" || $v12 == "激活" || $v12 == "激活成功" || $v12 == "待结算"){
//                                $orderInfo->order_status    = 4;
//                            }
//                        }
//                        if($v12 == "进行中" || $v12 == "已发货" || $v12 == "发货"){
//                            $orderInfo->order_status    = 2;
//                        }
//                        if($v12 == "已激活" || $v12 == "激活" || $v12 == "激活成功" || $v12 == "待结算"){
//                            $orderInfo->order_status    = 4;
//                        }

                        if($values[3] == '失败'){
                            $orderInfo->order_status    = 0;
                        }
                        if($values[3] == '进行中'){
                            $orderInfo->order_status    = 2;
                        }
                        if($values[3] == '完成'){
                            $orderInfo->order_status    = 5;
                        }
                        if(!empty($values[17])){
                            $orderInfo->shipping_company_name    = $values[17];
                        }
                        if(!empty($values[18])){
                            $orderInfo->shipping_no    = $values[18];
                        }
                        $orderInfo->import_num += 1;
                        if($orderInfo->order_status == 5){
                            //一次性结算
                            $orderInfo->settlement_time = time();
                            $orderInfo->baoxiao_time    = time();
                            $orderInfo->baoxiao_status  = 2;
                            $orderInfo->is_hexiao       = 2;
                            if($orderInfo['is_more'] == 1){
                                    jiesuan($orderInfo,$packageInfo,0);
                            }else {
                                    $orderInfo->is_hexiao      = 5;
                                    $orderInfo->baoxiao_status = 4;
                                    jiangli($orderInfo, $packageInfo);
                                    if ($orderInfo['parent_id']) {
                                        jiangli($orderInfo, $packageInfo, 2);
                                    }
                                    if ($orderInfo['two_id']) {
                                        jiangli($orderInfo, $packageInfo, 3);
                                    }
                                    //区县
                                    if ($orderInfo['agency_area_id']) {
                                        jiangli($v, $packageInfo, 4);
                                    }
                                    //小区
                                    if ($orderInfo['plot_id']) {
                                        jiangli($orderInfo, $packageInfo, 5);
                                    }
                                    if ($values[5]) {
                                        $orderInfo->is_hexiao      = 8;
                                        $orderInfo->baoxiao_status = 6;
                                        sleep(1);
                                        jiangli($orderInfo, $packageInfo, 1, 2);
                                        if ($orderInfo['parent_id']) {
                                            jiangli($orderInfo, $packageInfo, 2, 2);
                                        }
                                        if ($orderInfo['two_id']) {
                                            jiangli($orderInfo, $packageInfo, 3, 2);
                                        }
                                        //区县
                                        if ($orderInfo['agency_area_id']) {
                                            jiangli($v, $packageInfo, 4, 2);
                                        }
                                        //小区
                                        if ($orderInfo['plot_id']) {
                                            jiangli($orderInfo, $packageInfo, 5, 2);
                                        }
                                    }
                            }
                        }
                        if(!empty($values[7])){
                            $orderInfo->phone = $values[7];
                        }
//                        $orderInfo->audit_status    = 2;
                        $orderInfo->outTradeNo      = $values[1];
                        $orderInfo->error_msg       = '';
                        $orderInfo->save();
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        $this->success('ok');
    }

}
